use salvo::prelude::*;

mod routes;

pub async fn backend_server() {

    // println!("current_dir: {:?}", std::env::current_dir().unwrap());

    // let base_dir = std::env::current_dir()
    //     .unwrap()
    //     .join("./static")
    //     .canonicalize()
    //     .unwrap();
    // println!("Base Dir: {base_dir:?}");
    //
    // let cors = Cors::new()
    //     .allow_origin(["http://127.0.0.1:5800", "http://localhost:5800"])
    //     .allow_methods(vec![Method::GET, Method::POST, Method::DELETE])
    //     .allow_headers("authorization")
    //     .into_handler();


    // let router = Router::new()
    //     .get(hello)
    //     .push(
    //         Router::with_hoop(Compression::new().force_priority(true))
    //             .path("ws_chat")
    //             .get(StaticFile::new(base_dir.join("ws_chat.txt"))),
    //     )
    //     .push(
    //         Router::with_hoop(Compression::new().enable_brotli(CompressionLevel::Fastest))
    //             .path("sse_chat")
    //             .get(StaticFile::new(base_dir.join("sse_chat.txt"))),
    //     )
    //     .push(
    //         Router::with_hoop(Compression::new().enable_zstd(CompressionLevel::Fastest))
    //             .path("todos")
    //             .get(StaticFile::new(base_dir.join("todos.txt"))),
    //     )
    //     .push(
    //         Router::with_hoop(Compression::new().enable_gzip(CompressionLevel::Fastest))
    //             .path("<*path>")
    //             .get(StaticDir::new(base_dir)),
    //     );

    // let router = routes::build_routers().await;
    //
    // let service = Service::new(router)
    //     .hoop(Logger::new())
    //     .hoop(cors);
    let service = routes::create_service().await;
    let acceptor = TcpListener::new("0.0.0.0:8000").bind().await;
    Server::new(acceptor).serve(service).await;
}


pub async fn frontend_server() {
    #[handler]
    async fn index() -> Text<&'static str> {
        Text::Html(HTML_DATA)
    }

    let router = Router::new().get(index);
    let acceptor = TcpListener::new("0.0.0.0:8001").bind().await;
    Server::new(acceptor).serve(router).await;
}

const HTML_DATA: &str = r#"
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Salvo Cors</title>
</head>
<body>
<button id="btn">Load Content</button>
<div id="content"></div>
<script>
document.getElementById("btn").addEventListener("click", function() {
    fetch("http://127.0.0.1:5600/hello", {method: "POST", headers: {authorization: "abcdef"}}).then(function(response) {
        return response.text();
    }).then(function(data) {
        document.getElementById("content").innerHTML = data;
    });
});
</script>
</body>
</html>
"#;
